﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace Common
{
    public  class logGuradar
    {
        
        private static string txtFolderPath =  "log"+dizhi() + DateTime.Now.ToString("yyyyMM");
        private static string txtFilePath = string.Empty;

        private static object obj = new object();
        public static void  writeLog(string strLog)
        {
            try
            {
                System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ThreadPoolwriteLog), "【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "】"+strLog);
            }
            catch{}
        }

        public static string dizhi()
        {
            if (RuntimeInformation.OSDescription.Contains("Linux"))
               {
                  return "/";
               }else
               {
                return @"\";
               }
                
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="strLog"></param>
        public static void ThreadPoolwriteLog(object obj)
        {

             string  strLog = obj.ToString();
            lock (obj)
            {
                txtFilePath = txtFolderPath + dizhi()+ DateTime.Now.ToString("yyyyMMdd") + "0001.log";
                
                string filePath = getPath();

                deleWrite();

                FileStream fStream = null;
                try
                {
                    using (fStream = new FileStream(filePath, FileMode.Append))
                    {
                        StreamWriter sWriter = null;
                        try
                        {
                            using (sWriter = new StreamWriter(fStream))
                            {
                                sWriter.WriteLine(strLog);
                                sWriter.AutoFlush = true;
                                sWriter.Flush();
                                sWriter.Dispose();
                            }
                            fStream.Dispose();
                            fStream = null;
                        }
                        catch
                        {
                            if (sWriter != null)
                            {
                                sWriter.Dispose();
                                sWriter = null;
                            }
                        }
                    }
                }
                catch
                {
                    if (fStream != null)
                    {
                        fStream.Dispose();
                        fStream = null;
                    }
                }
            }
        }
        private  static string getPath()
        {
            try
            {
                string refPath = string.Empty;
                string tmpFolderPath = txtFolderPath;
                string tmpFilePath = txtFilePath;
                if (!Directory.Exists(tmpFolderPath))
                { //创建目录
                    Directory.CreateDirectory(tmpFolderPath);
                }
                refPath = chkPath(tmpFilePath);
                return refPath;
            }
            catch
            {
                return string.Empty;
            }
        }

        private static string chkPath(string strPath)
        {
            string refPath = string.Empty;
            if (!File.Exists(strPath))
            { //创建文件
                File.CreateText(strPath).Dispose();
            }
            FileInfo fInfo = new FileInfo(strPath);
            FileInfo fInfoCur = new FileInfo(txtFolderPath);
            Int64 len = fInfo.Length;
            if (len > 1024 * 1024 * 5)
            { //大于5M
                if (!fInfo.DirectoryName.Equals(txtFolderPath))
                { //文件夹是昨天的了（即过了0点）
                    getPath();
                }
                //否则
                string newFilePath = fInfo.DirectoryName + dizhi() + (Convert.ToDecimal(fInfo.Name.Substring(0, fInfo.Name.IndexOf("."))) + 1).ToString() + ".log";
                refPath = chkPath(newFilePath);
            }
            else
            { //小于5M
                refPath = strPath;
            }

            fInfo = null;
            fInfoCur = null;
            return refPath;
        }

        /// <summary>
        /// 删除七天以前的日志
        /// </summary>
        public static void deleWrite()
        {
            txtFilePath =  @"log"+dizhi();
            DateTime datime = DateTime.Now.AddDays(-30);
            string[] directory = Directory.GetDirectories(txtFilePath);
            if (directory.Count() < 1)
                return;
            foreach (string dic in directory)
            {
                string[] files = Directory.GetFiles(dic);
                if (files.Count() < 1)
                {
                    Directory.Delete(dic);
                    continue;
                }
                foreach (string file in files)
                {
                    DateTime deleDateTime = Directory.GetCreationTime(file);
                    if (deleDateTime < datime)
                        File.Delete(file);
                }
            }
        }
    }
}
